import os
import gpio
import mqtt
import BH1750
import SHT30class

host = '192.168.137.1'
port = 1883

n = mqtt.net_connect(host, port)

print('n = ', n)

# 1st param is network id
# 2nd param is the tx and rx buffer size, default value is 256
# 3rd param is the timeout value (ms), default value is 2000
# c = mqtt.client_init(n, 256, 2000)
c = mqtt.client_init(n)

print('c = ', c)

cd = mqtt.ConnData()

cd.mqtt_version = 3
cd.clean_session = 1
cd.client_id = 'emqx_test'
cd.keep_alive = 60
cd.username = ''
cd.password = '12345678'

print(cd.mqtt_version)
print(cd.clean_session)
print(cd.client_id)
print(cd.keep_alive)
print(cd.password)

r = mqtt.connect(c, cd)

print('r = ', r)

mp = mqtt.MsgParam()

mp.qos = 2
mp.retain = 0
mp.dup = 0
mp.id = 0

lht_topic = 'lht/test'

# 初始化BH1750和SHT30
i2c_id = 1
sda_pin = 0
scl_pin = 1
freq = 400000

bh1750 = BH1750.BH1750(i2c_id, sda_pin, scl_pin, freq)
sht30 = SHT30class.SHT30(i2c_id, sda_pin, scl_pin, freq)

# 打开BH1750和SHT30
bh1750.open()
sht30.open()

data_dict = {}

while mqtt.is_connected(c):
    # 读取温度和湿度
    temperature, humidity = sht30.read()
    # 读取光照强度
    light = bh1750.read()

    data_dict['temperature'] = temperature
    data_dict['humidity'] = humidity
    data_dict['light'] = light

    print(str(data_dict))

    r = mqtt.publish(c, lht_topic, mp, str(data_dict))

    print('Message published:', r)

    os.handle_event()
    os.sleep(2)

print('r = ', r)

r = mqtt.disconnect(c)

print('r = ', r)

r = mqtt.client_deinit(c)

print('r = ', r)

r = mqtt.net_disconnect(n)

print('r = ', r)

